/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2015-2018. All rights reserved.
 * Description: Signature Verify CBB Library
 * Author: tangzonglei
 * Create: 2015
 * History: 2018/11/23 yebin code rule fixes
 */
#include "../cmscbb_common/cmscbb_list.h"
#include "cmscbb_err_def.h"

CMSCBB_ERROR_CODE CmscbbListAdd(CmscbbListDummy* list, CVB_VOID* item)
{
    if (list == CVB_NULL || item == CVB_NULL) {
        return CMSCBB_ERR_CONTEXT_INVALID_PARAM;
    }

    if (list->num >= CVB_LIST_MAX_COUNT) {
        return CMSCBB_ERR_SYS_LIST_OVERFLOW;
    }

    list->data[list->num] = item;
    ++list->num;

    return CVB_SUCCESS;
}

CVB_VOID CmscbbListFree(CmscbbListDummy* list, CmscbbListFreeCallback freeCb)
{
    CVB_INT iter;

    if (list == CVB_NULL || freeCb == CVB_NULL) {
        return;
    }

    for (iter = 0; iter < (CVB_INT)list->num; ++iter) {
        freeCb(list->data[iter]);
    }

    list->num = 0;
}

/* use a improved bubble sort */
CMSCBB_ERROR_CODE CmscbbListSort(CmscbbListDummy* list, CmscbbListItemCmpCallback cmpCb)
{
    CVB_INT iter1;
    CVB_INT iter2;
    /* check if last sort already done */
    CVB_INT flag;

    if (list == CVB_NULL || cmpCb == CVB_NULL) {
        return CMSCBB_ERR_CONTEXT_INVALID_PARAM;
    }

    flag = 1;
    for (iter1 = 0; (iter1 < (CVB_INT)list->num) && (flag == 1); ++iter1) {
        const CVB_INT nCmp = 2;
        CVB_INT beginIndex = (CVB_INT)list->num - nCmp;
        flag = 0;
        for (iter2 = beginIndex; iter2 >= iter1; --iter2) {
            if (cmpCb(list->data[iter2], list->data[iter2 + 1]) > 0) {
                /* swap two element */
                CVB_VOID* temp = list->data[iter2];
                list->data[iter2] = list->data[iter2 + 1];
                list->data[iter2 + 1] = temp;
                flag = 1;
            }
        }
    }

    return CVB_SUCCESS;
}
